import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import { compose, filter } from 'ramda';
import withStyles from '@mui/styles/withStyles';
import Typography from '@mui/material/Typography';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import { Link } from 'react-router-dom';
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction';
import IconButton from '@mui/material/IconButton';
import { LinkOff } from '@mui/icons-material';
import { HexagonOutline } from 'mdi-material-ui';
import { graphql, createFragmentContainer } from 'react-relay';
import AddSoftwares from './AddSoftwares';
import { addSoftwaresMutationRelationDelete } from './AddSoftwaresLines';
import { commitMutation } from '../../../../relay/environment';
import inject18n from '../../../../components/i18n';
import { truncate } from '../../../../utils/String';

const styles = (theme) => ({
  avatar: {
    width: 24,
    height: 24,
    backgroundColor: theme.palette.primary.main,
  },
  avatarDisabled: {
    width: 24,
    height: 24,
  },
  placeholder: {
    display: 'inline-block',
    height: '1em',
    backgroundColor: theme.palette.grey[700],
  },
});

class VulnerabilitySoftwaresComponent extends Component {
  removeSoftware(softwareEdge) {
    commitMutation({
      mutation: addSoftwaresMutationRelationDelete,
      variables: {
        fromId: softwareEdge.node.id,
        toId: this.props.vulnerability.id,
        relationship_type: 'has',
      },
      updater: (store) => {
        const node = store.get(this.props.vulnerability.id);
        const softwares = node.getLinkedRecord('softwares', { first: 10 });
        const edges = softwares.getLinkedRecords('edges');
        const newEdges = filter((n) => n.getLinkedRecord('node').getValue('id') !== softwareEdge.node.id, edges);
        softwares.setLinkedRecords(newEdges, 'edges');
      },
    });
  }

  render() {
    const { t, vulnerability } = this.props;
    return (
      <div style={{ height: '100%', marginTop: 20 }}>
        <Typography variant="h3" gutterBottom={true} style={{ float: 'left' }}>
          {t('Affected software')}
        </Typography>
        <AddSoftwares
          vulnerability={vulnerability}
          vulnerabilitySoftwares={vulnerability.softwares.edges}
        />
        <div className="clearfix" />
        <List style={{ marginTop: -10 }}>
          {vulnerability.softwares.edges.map((softwareEdge) => {
            const software = softwareEdge.node;
            return (
              <ListItem
                key={software.id}
                dense={true}
                divider={true}
                button={true}
                component={Link}
                to={`/dashboard/observations/observables/${software.id}`}
              >
                <ListItemIcon>
                  <ListItemIcon>
                    <HexagonOutline color="primary" />
                  </ListItemIcon>
                </ListItemIcon>
                <ListItemText
                  primary={`${software.name} ${
                    software.version && software.version.length > 0
                      ? `(${software.version})`
                      : ''
                  }`}
                  secondary={truncate(software.x_opencti_description, 120)}
                />
                <ListItemSecondaryAction>
                  <IconButton
                    aria-label="Remove"
                    onClick={this.removeSoftware.bind(this, softwareEdge)}
                    size="large"
                  >
                    <LinkOff />
                  </IconButton>
                </ListItemSecondaryAction>
              </ListItem>
            );
          })}
        </List>
      </div>
    );
  }
}

VulnerabilitySoftwaresComponent.propTypes = {
  classes: PropTypes.object,
  t: PropTypes.func,
  fld: PropTypes.func,
  vulnerability: PropTypes.object,
};

const VulnerabilitySoftwares = createFragmentContainer(
  VulnerabilitySoftwaresComponent,
  {
    vulnerability: graphql`
      fragment VulnerabilitySoftwares_vulnerability on Vulnerability {
        id
        name
        parent_types
        entity_type
        softwares(first: 10) {
          edges {
            node {
              id
              parent_types
              x_opencti_description
              ... on Software {
                name
                version
                vendor
              }
            }
          }
        }
      }
    `,
  },
);

export default compose(inject18n, withStyles(styles))(VulnerabilitySoftwares);
